package com.lishangshan.oas_system.controller.attendce;

import com.lishangshan.oas_system.model.dao.attendcedao.AttendceDao;
import com.lishangshan.oas_system.model.dao.attendcedao.AttendceService;
import com.lishangshan.oas_system.model.dao.system.StatusDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.dao.user.UserService;
import com.lishangshan.oas_system.model.entity.attendce.Attends;
import com.lishangshan.oas_system.model.entity.system.SystemStatusList;
import com.lishangshan.oas_system.model.entity.system.SystemTypeList;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.utils.StringtoDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class AttendceConFun {
    @Autowired
    private AttendceDao attendceDao;
    @Autowired
    AttendceDao attenceDao;
    @Autowired
    AttendceService attendceService;
    @Autowired
    UserDao uDao;
    @Autowired
    UserService userService;
    @Autowired
    TypeDao typeDao;
    @Autowired
    StatusDao statusDao;
    // 格式转化导入
    DefaultConversionService service = new DefaultConversionService();
    Date start, end;
    String month_;

    /**
     * 单个页面 个人 用户考勤 信息 全查 初始化方法
     *
     * @param request
     * @param model
     * @param session
     * @param page
     * @param baseKey
     * @param type
     * @param status
     * @param time
     * @param icon
     */
    public void signsortpaging(HttpServletRequest request, Model model, HttpSession session, int page, String baseKey,
                               String type, String status, String time, String icon) {
        Long userid = Long.valueOf(session.getAttribute("userId") + "");
        Page<Attends> page2 = attendceService.singlepage(page, baseKey, userid, type, status, time);
        typestatus(request);
        request.setAttribute("baseKey", baseKey);
        request.setAttribute("alist", page2.getContent());
        request.setAttribute("page", page2);
        request.setAttribute("url", "attendcelisttable");
    }

    /**
     * 用户 考勤 状态 存值
     *
     * @param request
     */
    // 状态类型方法
    public void typestatus(HttpServletRequest request) {
        List<SystemTypeList> type = (List<SystemTypeList>) typeDao.findByTypeModel("aoa_attends_list");
        List<SystemStatusList> status = (List<SystemStatusList>) statusDao.findByStatusModel("aoa_attends_list");
        request.setAttribute("typelist", type);
        request.setAttribute("statuslist", status);
    }

    /**
     * 存储 相关 值 的方法 存储 排序规则
     *
     * @param baseKey
     * @param type
     * @param status
     * @param time
     * @param icon
     * @param model
     */
    //存储相关参数值
    public void setSomething(String baseKey, Object type, Object status, Object time, Object icon, Model model) {
        if (!StringUtils.isEmpty(icon)) {
            model.addAttribute("icon", icon);
            if (!StringUtils.isEmpty(type)) {
                model.addAttribute("type", type);
                if ("1".equals(type)) {
                    model.addAttribute("sort", "&type=1&icon=" + icon);
                } else {
                    model.addAttribute("sort", "&type=0&icon=" + icon);
                }
            }
            if (!StringUtils.isEmpty(status)) {
                model.addAttribute("status", status);
                if ("1".equals(status)) {
                    model.addAttribute("sort", "&status=1&icon=" + icon);
                } else {
                    model.addAttribute("sort", "&status=0&icon=" + icon);
                }
            }
            if (!StringUtils.isEmpty(time)) {
                model.addAttribute("time", time);
                if ("1".equals(time)) {
                    model.addAttribute("sort", "&time=1&icon=" + icon);
                } else {
                    model.addAttribute("sort", "&time=0&icon=" + icon);
                }
            }
        }
        if (!StringUtils.isEmpty(baseKey)) {
            model.addAttribute("sort", "&baseKey=" + baseKey);
        }
    }

    /**
     * 向 考勤 管理列表查询 下级员工 中的考勤记录并 存储数据
     *
     * @param request
     * @param session
     * @param page
     * @param baseKey
     * @param type
     * @param status
     * @param time
     * @param icon
     * @param model
     */
    //该管理下面的所有用户
    public void allsortpaging(HttpServletRequest request, HttpSession session, int page, String baseKey, String type,
                              String status, String time, String icon, Model model) {
        setSomething(baseKey, type, status, time, icon, model);
        Long userId = Long.parseLong(session.getAttribute("userId") + "");
        List<Long> ids = new ArrayList<>();
        List<User> users = uDao.findByFatherId(userId);
        for (User user : users) {
            ids.add(user.getUserId());
        }
        if (ids.size() == 0) {
            ids.add(0L);
        }
        User user = uDao.findOne(userId);
        typestatus(request);
        Page<Attends> page2 = attendceService.paging(page, baseKey, ids, type, status, time);
        request.setAttribute("alist", page2.getContent());
        request.setAttribute("page", page2);
        request.setAttribute("url", "attendcetable");
    }

    /**
     * 周报表 分页 方法
     *
     * @param request
     * @param session
     * @param page
     * @param baseKey
     */
    //周报表分页
    public void weektablepaging(HttpServletRequest request, HttpSession session, int page, String baseKey) {

        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");

        System.out.println(starttime + " " + endtime);
        // 格式转化
        service.addConverter(new StringtoDateUtil());
        Date startdate = service.convert(starttime, Date.class);
        Date enddate = service.convert(endtime, Date.class);

        System.out.println(starttime + " " + endtime);

        //用来查找该用户下面管理的所有用户信息
        Long userId = Long.parseLong(session.getAttribute("userId") + "");
        List<Long> ids = new ArrayList<>();
        Page<User> userspage = userService.findmyemployuser(page, baseKey, userId);
        for (User user : userspage) {
            ids.add(user.getUserId());
        }
        if (ids.size() == 0) {
            ids.add(0L);
        }

        //找到某个管理员下面的所有用户的信息 保证传过来的是正确的数据 分页之后可以使用全局变量来记住开始和结束日期
        if (startdate != null && enddate != null) {
            start = startdate;
            end = enddate;
        }
        if (startdate == null && enddate == null) {
            startdate = start;
            enddate = end;
        }


        List<Attends> alist = attenceDao.findoneweek(startdate, enddate, ids);
        Set<Attends> attenceset = new HashSet<>();
        for (User user : userspage) {
            for (Attends attence : alist) {
                if (Objects.equals(attence.getUser().getUserId(), user.getUserId())) {
                    attenceset.add(attence);
                }
            }
            user.setaSet(attenceset);
        }
        String[] weekday = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        request.setAttribute("ulist", userspage.getContent());
        request.setAttribute("page", userspage);
        request.setAttribute("weekday", weekday);
        request.setAttribute("url", "realweektable");
    }

    /**
     * 月 报表 分页 方法
     *
     * @param request
     * @param model
     * @param session
     * @param page
     * @param baseKey
     */
    public void monthtablepaging(HttpServletRequest request, Model model, HttpSession session, int page,
                                  String baseKey) {
        Integer offnum, toworknum;
        Long userId = Long.parseLong(session.getAttribute("userId") + "");
        List<Long> ids = new ArrayList<>();
        Page<User> userspage = userService.findmyemployuser(page, baseKey, userId);
        for (User user : userspage) {
            ids.add(user.getUserId());
        }
        if (ids.size() == 0) {
            ids.add(0L);
        }
        String month = request.getParameter("month");

        if (month != null)
            month_ = month;
        else
            month = month_;

        Map<String, List<Integer>> uMap = new HashMap<>();
        List<Integer> result = null;

        for (User user : userspage) {
            result = new ArrayList<>();
            //当月该用户下班次数
            offnum = attenceDao.countoffwork(month, user.getUserId());
            //当月该用户上班次数
            toworknum = attenceDao.counttowork(month, user.getUserId());
            for (long statusId = 10; statusId < 13; statusId++) {
                //这里面记录了正常迟到早退等状态
                if (statusId == 12)
                    result.add(attenceDao.countnum(month, statusId, user.getUserId()) + toworknum - offnum);
                else
                    result.add(attenceDao.countnum(month, statusId, user.getUserId()));
            }
            //添加请假和出差的记录//应该是查找 使用sql的sum（）函数来统计出差和请假的次数
            System.out.println("请假天数" + attenceDao.countothernum(month, 46L, user.getUserId()));
            if (attenceDao.countothernum(month, 46L, user.getUserId()) != null)
                result.add(attenceDao.countothernum(month, 46L, user.getUserId()));
            else
                result.add(0);
            if (attenceDao.countothernum(month, 47L, user.getUserId()) != null)
                result.add(attenceDao.countothernum(month, 47L, user.getUserId()));
            else
                result.add(0);
            //这里记录了旷工的次数 还有请假天数没有记录 旷工次数=30-8-请假次数-某天签到次数
            //这里还有请假天数没有写
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            String date_month = sdf.format(date);
            if (month != null) {
                if (month.compareTo(date_month) >= 0)
                    result.add(0);
                else
                    result.add(30 - 8 - offnum);
            }

            uMap.put(user.getUserName(), result);
        }
        model.addAttribute("uMap", uMap);
        model.addAttribute("ulist", userspage.getContent());
        model.addAttribute("page", userspage);
        model.addAttribute("url", "realmonthtable");
    }
}
